package xin.nick.common.interceptor;

import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import xin.nick.common.constant.SystemConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * mdc 日志配置拦截器
 * @author Nick
 * @since 2022/1/27
 */
@Slf4j
@Component
public class MdcInterceptor implements HandlerInterceptor {

    /**
     * 进入前处理添加MDC的 requestId
     * @param request
     * @param response
     * @param handler
     * @return boolean
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        // 添加MDC
        String requestId = IdUtil.fastSimpleUUID();
        MDC.put(SystemConstants.REQUEST_ID, requestId);

        try {
            log.info("URI(Itp)在AOP之前: {}", request.getRequestURI());
        } catch(Exception e) {
            log.error("请求日志打印出错", e);
        }

        return true;
    }

}
